package com.molichuxing.services.sdk.fico;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSession;
import javax.net.ssl.SSLSocket;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.AllowAllHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContextBuilder;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.conn.ssl.X509HostnameVerifier;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;


@Component
public class FicoLib {

    private static Logger loger = Logger.getLogger(FicoLib.class);

    private static String clientId;
    private static String password;
    private static String creditInvestigationUrl;
    private static String abc;

    @Value("${fico.client.id}")
  	public  void setClientId(String clientId) {
  		FicoLib.clientId = clientId;
  	}

    @Value("${fico.password}")
  	public  void setPassword(String password) {
  		FicoLib.password = password;
  	}

    @Value("${fico.credit.investigation.url}")
  	public  void setCreditInvestigationUrl(String creditInvestigationUrl) {
  		FicoLib.creditInvestigationUrl = creditInvestigationUrl;
  	}
    

    public static String creditInvestigation(String phoneNumber,String idCard,String fullName,String txnID,Integer businessType,Integer price)throws Exception{
        String xmlTemplate =
                "<Request clientID=\"%s\" password=\"%s\" serviceCode=\"601\">\n" +
                "<Application txnID=\"%s\" product=\"BQ\">\n" +
                "    <Applicant mobile=\"%s\" idCard=\"%s\" name=\"%s\" businessType=\"%s\" price=\"%s\" />\n" +
                "</Application>" +
                "</Request>";
        String requestXml=String.format(xmlTemplate,clientId,password,txnID,phoneNumber,idCard,fullName,businessType,price);
        loger.info("发送给fico征信认证接口的requestXML："+requestXml);
        return httpPost(requestXml,creditInvestigationUrl);
    }

    private static String httpPost(String body,String url) throws Exception {
        loger.info("开始调用fico征信认证接口.....");
        HttpClient client = createSSLClientDefault();
        RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(5000).setConnectTimeout(5000).build();//设置请求和传输超时时间
        HttpPost post = new HttpPost(url);
        post.setConfig(requestConfig);
        post.setEntity(new StringEntity(body,"utf-8"));
        HttpResponse response = client.execute(post);
        HttpEntity httpEntity = response.getEntity();

        String result = EntityUtils.toString(httpEntity,"utf-8");
        loger.info("调用fico征信认证接口结果："+result);
        return result;
    }


    private static CloseableHttpClient createSSLClientDefault() throws Exception{
        try {
//            KeyStore keyStore = KeyStore.getInstance(KeyStore.getDefaultType());
//
//            // get user password and file input stream
//            char[] password =cacertsPassword.toCharArray();
//
//            java.io.FileInputStream fis = null;
//            try {
//                fis = new java.io.FileInputStream(cacertsPath);
//                keyStore.load(fis, password);
//            } finally {
//                if (fis != null) {
//                    fis.close();
//                }
//            }
//            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(keyStore).build();
//            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext);
//
//            return HttpClients.custom().setSSLSocketFactory(sslsf).build();

            SSLContext sslContext = new SSLContextBuilder().loadTrustMaterial(null, new TrustStrategy(){
                public boolean isTrusted(java.security.cert.X509Certificate[] x509Certificates, String s) throws java.security.cert.CertificateException {
                    return true; }
            }).build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext,new AllowAllHostnameVerifier());
            return HttpClients.custom().setSSLSocketFactory(sslsf).setHostnameVerifier(new X509HostnameVerifier() {
                @Override
                public boolean verify(String s, SSLSession sslSession) {
                    return true;
                }

                @Override
                public void verify(String s, SSLSocket sslSocket) throws IOException {

                }

                @Override
                public void verify(String s, X509Certificate x509Certificate) throws SSLException {

                }

                @Override
                public void verify(String s, String[] strings, String[] strings1) throws SSLException {

                }
            }).build();


        } catch (KeyManagementException e) {
            e.printStackTrace();
            throw new Exception("创建ssl客户端异常");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
            throw new Exception("创建ssl客户端异常");
        } catch (KeyStoreException e) {
            e.printStackTrace();
            throw new Exception("创建ssl客户端异常");
        }
    }
}
